package com.foreknow.controller;

import com.foreknow.bean.User;
import com.foreknow.service.UserService;
import com.foreknow.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * servlet:服务器端的应用程序
 * 1. 需要继承 HttpServlet
 * 2. 重写doGet/doPost方法
 *    这两个方法会根据前端的语法来调用
 *    如果前端发送的请求是get请求(例如：<a>链接<a/>)就会自动调用Servlet中的doGet方法
 *    如果前端发送的请求是post请求(例如：<form method="post">表单<form/>)就会自动调用Servlet中的doPost方法
 * 3. HttpServletRequest 请求对象
 * 4. HttpServletResponse 响应对象
 */
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //服务器向客户端响应的内容的类型
        //        resp.setContentType("text/html;charset=utf-8");
        //        //获取PrintWriter打印流 作用是向网页写一些基本的信息
        //        PrintWriter out = resp.getWriter();
        //        out.println("<html>");
        //        out.println("<head>");
        //        out.println("<title>servlet</title>");
        //        out.println("</head>");
        //        out.println("<body>");
        //        out.println(new Date());
        //        out.println("</body>");
        //        out.println("</html>");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        //向网页响应内容
        PrintWriter out = resp.getWriter();
        //request对象中的其它方法测试
        //        out.println("获取请求方法的名称："+ req.getMethod());
        //        out.println("获取访问项目的Application Conext的名称："+ req.getContextPath());
        //        out.println("获取请求的URI地址："+ req.getRequestURL());

        //获取前端请求的参数 name="tom"&password=123456   java.lang.String getParameter(java.lang.String name)
        // <input type="text" id="inputEmail" name="username" class="form-control" placeholder="Email address" required autofocus>
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //调用Service中的登录方法
        UserService service = new UserServiceImpl();
        User user = service.isValidate(username,password);
        if(user!=null) {
            //            out.println("<a href=''>查看所有写留言的信息</a>");
            //            out.println(username+"-----------------------"+password);
            //请求转发
                        req.getRequestDispatcher("/manager?q=list").forward(req,resp);
            //重定向
//            resp.sendRedirect(req.getContextPath()+"/get");


        }else {
            out.println("error......");
        }
    }
}
